var SSO = (window.SSO = {
  conf: {
    url: 'https://sso.xfyun.cn/SSOService',
  },
  init() {
    // 去除地址栏中的token/account_id/accountId/ssoSessionId
    window.history.replaceState(
      window.history.state,
      '',
      SSO.utils.setQueryString({
        token: '',
        account_id: '',
        accountId: '',
        ssoSessionId: '',
      })
    );
  },
  /**
   * 退出登录
   * @param loggedOutCallback 退出后的回调函数
   */
  logout(loggedOutCallback) {
    loggedOutCallback && (SSO.utils.loggedOutCallback = loggedOutCallback);
    SSO.utils.sendJSONP('/login/do-logout', {
      callback: 'SSO.utils.logoutJSONPCallback',
      ssoSessionId: SSO.utils.getCookie('ssoSessionId'),
      isJsonp: 'true',
    });
  },
  utils: {
    /**
     * 设置地址栏中的参数
     * @param queryObj
     * @param url
     * @returns {string}
     */
    setQueryString: (queryObj, url) => {
      url = url || window.location.href;
      const urlArr = url.split('?');
      let searchArr = [];
      let searchItem;
      const searchObj = {};
      let queryStr = '';
      if (urlArr.length > 1) {
        searchArr = urlArr[1].split('&');
      }
      for (let i = 0; i < searchArr.length; i++) {
        try {
          searchItem = searchArr[i].split('=');
          searchObj[searchItem[0]] = searchItem[1];
        } catch (e) {
          console.log(e);
        }
      }
      for (const p in queryObj) {
        searchObj[p] = queryObj[p];
      }
      for (const p in searchObj) {
        if (searchObj[p]) {
          queryStr += `&${p}=${searchObj[p]}`;
        }
      }
      queryStr = queryStr.replace('&', '?');
      return urlArr[0] + queryStr;
    },
    sendJSONP: (url, queryJson, callback) => {
      queryJson = queryJson || {};
      queryJson._ = new Date().getTime();
      const script = document.createElement('script');
      script.src = SSO.utils.setQueryString(queryJson, SSO.conf.url + url);
      document.head.appendChild(script);
      script.onload = function () {
        callback && callback();
        document.head.removeChild(script);
      };
    },
    getCookie: (key) => {
      return document.cookie
        .split(';')
        .map((x) => (x.indexOf(key) > -1 ? x : ''))
        .join('')
        .split(`${key}=`)[1];
    },
    logoutJSONPCallback: (ssoSessionId) => {
      SSO.utils.setLocalCookie(ssoSessionId, '');
      SSO.utils.loggedOutCallback();
    },
    setLocalCookie: (ssoSessionId, accountId) => {
      document.cookie = `ssoSessionId=${ssoSessionId}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/`;
      document.cookie = `account_id=${accountId}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/`;
    },
    loggedOutCallback: () => {
      // 默认退出回调
      window.location.reload();
    },
  }
})

/* 退出 */
function logOutApi() {
  SSO.init()
  SSO.logout().then(() => {
      
    // console.log('success')
    // window.location.reload()
  })
}